How to replace the char '[' etc with '\[' using "sed" in a file ?

Posted by Abhijeet on Stack Overflow See other posts from Stack Overflow or by Abhijeet
Published on 2011-01-14T06:48:07Z Indexed on 2011/01/14 6:53 UTC
Read the original article Hit count: 140

Filed under:
|
|

I have a file say "file.txt" with following contents:

Capsule arr**[**0**]** in state A
rate_ul/dl=**(**2000000/7000000**)**
Capsule RBx**[**0**]** in state
...
...

using sed operator how can i replace all occurences of '[' with '[', '(' with '(', ']' with ']' and so on.

Capsule arr**\[**0**\]** in state A
rate_ul/dl=**\(**2000000/7000000**\)**
Capsule RBx**\[**0**\]** in state
...
...

Using the substitue operator in "gvim" I am able to achieve the same result. ie. if i use ":1,$ s/\[/\\[/g" in the vi editor in command mode I see all the '[' chars replaced with '['.

However if I try to use the same substitue command in a shell script using a sed command, i am not able to achieve the same result. ie If i use the following command in a shell script I am not able to achieve the desired result:

sed "s/\[/\\[/g"  $temp_file2 > $temp_file1
where $temp_file2 conatins the lines with '[' characters and $temp_file1 should contain the replaced '\[' chars

© Stack Overflow or respective owner

Related posts about shell

Related posts about sed